﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Candy_Eyes_Pro;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.Win32;
using FilmOnline;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace ZingMp3
{
    public partial class frmMain : Form
    {
        List<string> urls;
        List<string> titles;
        List<string> artists;
        List<int> ids;
        List<string> fileNames;
        string strWating = "Đang chờ";
        string strOK = "Đã gửi";
        public frmMain()
        {
            InitializeComponent();
            this.Icon = Properties.Resources._561268_350181961684928_1949511752_n_1_;
            imageList1.Images.Add(Properties.Resources.mp3_file_icon);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnTimBaiHat_Click(object sender, EventArgs e)
        {
            lbComplete.Visible = false;
            checkBox1.Checked = false;
            //try
            //{
            listView1.Items.Clear();
            Html html = new Html();
            if (!txtUrl.Text.Contains("?")) txtUrl.Text += "?by=kida7";
            string source = html.ReadUrl(txtUrl.Text);
            Regex xmlURL = new Regex(@"<param.+xmlURL=(?<url>[^&]+)");
            Regex albumTitle = new Regex(@"<h1[^>]+>(?<title>[^<]+)<");//xmlUrl:'[^']+'
            Match match = xmlURL.Match(source);
            if (!match.Success)
            {
                xmlURL = new Regex(@"xmlURL:'(?<url>[^']+)'");
                match = xmlURL.Match(source);
            }
            if (!match.Success)
            {
                MessageBox.Show("Không thể phân tích URL");
                return;
            }
            Match matchTitle = albumTitle.Match(source);
            XmlDocument xml = new XmlDocument();

            string xmlUrl = match.Groups["url"].ToString();

            //xml.Load(match.Groups["url"].ToString());
            string xmlString = html.ReadUrl(xmlUrl);
            //MessageBox.Show(xmlString);
            xml.LoadXml(xmlString);

            this.Text = matchTitle.Groups["title"].ToString();
            
            XmlNodeList nodes = xml.SelectNodes("//item");

            //MessageBox.Show(nodes.Count.ToString());
            //try
            //{
            //	WMPLib.IWMPPlaylistArray ar =  wmp.playlistCollection.getByName("playlist");
            //	wmp.playlistCollection.remove(ar.Item(0));
            //}
            //catch(Exception)
            //{}
            //playlist = wmp.playlistCollection.newPlaylist("playlist");

            foreach (XmlNode node in nodes)
            {
                //MessageBox.Show(node.ToString());
                ListViewItem item = new ListViewItem("", 0);
                item.SubItems.Add("");
                item.SubItems.Add("");
                item.SubItems.Add("");
                foreach (XmlNode child in node.ChildNodes)
                {

                    switch (child.Name)
                    {
                        case "title":
                            item.Text = child.InnerText;
                            break;
                        case "performer":
                            item.SubItems[1].Text = (child.InnerText);
                            break;
                        case "source":
                            item.SubItems[2].Text = (child.InnerText);
                            break;
                    }
                }
                item.SubItems[3].Text = (strWating);
                listView1.Items.Add(item);
                //WMPLib.IWMPMedia media = wmp.newMedia(item.SubItems[2].Text);
                //playlist.appendItem(media);

            }
            //wmp.currentPlaylist = playlist;
            lbSongsCount.Text = String.Format("Có {0} bài hát trong album!", nodes.Count);
            lbSongsCount.Visible = true;

            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FileInfo file = new FileInfo(txtIDM.Text);
            if (!file.Exists)
            {
                MessageBox.Show("Bạn chưa cài IDM! Nếu bạn cài rồi mà vẫn gặp thông báo này \nthì hãy xóa đường dẫn trong ô cấu hình IDM và bật lại chương trình");
                return;
            }
            lbComplete.Visible = false;
            lbSongsCount.Visible = false;
            FileInfo f = new FileInfo(txtIDM.Text);
            DirectoryInfo d = new DirectoryInfo(txtFolder.Text);
            if (!d.Exists || !f.Exists)
            {
                MessageBox.Show("Thu muc luu nhac khong ton tai");
                return;
            }

            urls = new List<string>();
            titles = new List<string>();
            artists = new List<string>();
            int i = 0;
            ids = new List<int>();
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.Checked && item.SubItems[3].Text != strOK)
                {
                    titles.Add(item.Text);
                    artists.Add(item.SubItems[1].Text);
                    urls.Add(item.SubItems[2].Text);
                    ids.Add(i);
                }
                i++;
            }
            fileNames = new List<string>();
            progressBar1.Value = 0;
            //MessageBox.Show(urls.Count+"");
            backgroundWorker1.RunWorkerAsync();
            //pictureBox1.Visible = true;
            progressBar1.Visible = true;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int n = urls.Count;
            for (int i = 0; i < urls.Count; i++)
            {
                Process p = new Process();
                p.StartInfo.FileName = txtIDM.Text;
                string fileName = RemoveSpecialString(titles[i]) + " - " + RemoveSpecialString(artists[i]);

                string args = String.Format("/d \"{0}\" /p \"{1}\" /f \"{2}.mp3\" /a", urls[i], txtFolder.Text + "\\" + RemoveSpecialString(this.Text), fileName);
                p.StartInfo.Arguments = args;
                if (!fileNames.Contains(fileName))
                {
                    fileNames.Add(fileName);
                    p.Start();
                }
                Thread.Sleep(200);
                backgroundWorker1.ReportProgress(100 * (i + 1) / n, ids[i]);
            }
        }

        void GetSongInfo(string url)
        {
            Regex regex = new Regex(@"/(?<id?>[^/\.]+)\.html");
            Match match = regex.Match(url);
            Html html = new Html();
            string str = html.ReadUrl("http://mp3.zing.vn/play/?pid=" + match.Groups["id"].ToString() + "||4&songID=0");
            MessageBox.Show(str);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            listView1.Items[(int)e.UserState].SubItems[3].Text = strOK;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtIDM.Text = Properties.Settings.Default.txtIDM;
            txtFolder.Text = Properties.Settings.Default.txtFolder;
            txtUrl.Text = Properties.Settings.Default.txtUrl;

            if (txtIDM.Text == "")
            {
                txtIDM.Text = Registry.GetValue(@"HKEY_CURRENT_USER\Software\DownloadManager\", "ExePath", null).ToString();
                
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

            foreach (ListViewItem item in listView1.Items)
            {
                item.Checked = checkBox1.Checked;
            }
        }
        string RemoveSpecialString(string str)
        {
            String s = Language.RemoveSign4VietnameseString(str);
            char[] chars = Path.GetInvalidFileNameChars();
            foreach (char c in chars) s = s.Replace(c, '-');
            s = s.Trim();
            s = Regex.Replace(s, @"[^\u0000-\u007F]", string.Empty);
            return s;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = txtIDM.Text;
            p.StartInfo.Arguments = "/s";
            p.Start();
            progressBar1.Visible = false;
            lbComplete.Visible = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFolder.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.txtFolder = txtFolder.Text;
            Properties.Settings.Default.txtIDM = txtIDM.Text;
            Properties.Settings.Default.txtUrl = txtUrl.Text;
            Properties.Settings.Default.Save();
        }

        private void button5_Click(object sender, EventArgs e)
        {

        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) return;

        }
    }
}
